import { createRouter, createWebHashHistory } from "vue-router";

const routes = [
  {
    //访问 / 路径时重定向到 login 页面
    path: "/",redirect: "/login"
  },
  {
    path: "/login",
    name: "Login",
    component: ()=>import("../components/Login.vue")
  },
  
  {
    path: "/home",
    name: "Home",
    //访问home路径时重定向到welcome
    redirect: "/welcome",
    //子路由
    children:[
      {
        path: "/welcome",
        name: "Welcome",
        component: ()=>import("../components/Welcome.vue")
      },
      {
        path: "/user",
        name: "User",
        component: ()=>import("../components/User.vue")
      },
      {
        path: "/student",
        name: "Student",
        component: ()=>import("../components/Student.vue")
      },
      {
        path: "/hello",
        name: "Hello",
        component: ()=>import("../components/Hello.vue")
      },
  ],
    component: ()=>import("../components/Home.vue")
  },
  
  // {
  //   path: "/about",
  //   name: "About",
  //   // route level code-splitting
  //   // this generates a separate chunk (about.[hash].js) for this route
  //   // which is lazy-loaded when the route is visited.
  //   component: () =>
  //     import(/* webpackChunkName: "about" */ "../views/About.vue")
  // }
];

const router = createRouter({
  history: createWebHashHistory(),
  routes,
})

//路由守卫
router.beforeEach((to, from, next) => {
  //to 将要访问的路径
  //from 代表从那个路径而来
  //next()代表放行 next(xxx) 强制放行的xxx的路径
  if(to.path==='/'||to.path==='/login'){
    //登录页或空路径放行
    next();
  }else{
    //获取浏览器 localStorage 里的token，没有就重定向到 login
    const tokenStr = window.localStorage.getItem('token')
    if (!tokenStr) {
      return next('/login')
    }
    //有 token 就放行
    next();
  }
})


export default router;
